"""
连接视图模块 - PyQt5版本
提供COM口选择、CAN ID配置和连接管理功能
"""
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, 
                             QPushButton, QLabel, QComboBox, QLineEdit,
                             QFrame, QGridLayout, QSizePolicy)
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QFont, QValidator


class DecimalValidator(QValidator):
    """10进制验证器"""
    
    def __init__(self, min_val=0, max_val=2047, parent=None):
        super().__init__(parent)
        self.min_val = min_val
        self.max_val = max_val
        
    def validate(self, input_str, pos):
        """验证输入是否为有效的10进制数"""
        if not input_str:
            return QValidator.Intermediate, input_str, pos
            
        try:
            value = int(input_str)
            if self.min_val <= value <= self.max_val:
                return QValidator.Acceptable, input_str, pos
            else:
                return QValidator.Invalid, input_str, pos
        except ValueError:
            if input_str.isdigit() or (input_str == '' and pos == 0):
                return QValidator.Intermediate, input_str, pos
            else:
                return QValidator.Invalid, input_str, pos


class ConnectionView(QWidget):
    """连接视图类 - PyQt5版本"""
    
    # 信号定义
    connect_requested = pyqtSignal(dict)  # 连接请求信号
    disconnect_requested = pyqtSignal()  # 断开连接信号
    refresh_ports_requested = pyqtSignal()  # 刷新COM口信号
    
    def __init__(self, parent=None):
        """初始化连接视图"""
        super().__init__(parent)
        
        # 界面组件
        self._com_port_combo = None
        self._tx_can_id_combo = None
        self._rx_can_id_combo = None
        self._baudrate_combo = None
        self._connect_btn = None
        self._disconnect_btn = None
        self._refresh_btn = None
        self._status_label = None
        
        # 连接状态
        self._is_connected = False
        self._is_connecting = False
        
        # 创建界面
        self._setup_ui()
        
        # 设置初始状态
        self._update_button_states()
    
    def _setup_ui(self):
        """设置用户界面"""
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(layout)
        
        # 连接配置区域
        config_group = self._create_config_group()
        layout.addWidget(config_group)
        
        # 连接控制区域
        control_layout = self._create_control_layout()
        layout.addLayout(control_layout)
        
        # 连接状态区域
        status_group = self._create_status_group()
        layout.addWidget(status_group)
    
    def _create_config_group(self):
        """创建配置区域"""
        group = QGroupBox("连接配置")
        layout = QGridLayout()
        group.setLayout(layout)
        
        # 第一行：COM口配置
        com_label = QLabel("COM口:")
        com_label.setFixedWidth(60)
        layout.addWidget(com_label, 0, 0)
        
        self._com_port_combo = QComboBox()
        self._com_port_combo.setMinimumWidth(100)
        self._com_port_combo.addItem("请选择COM口")
        layout.addWidget(self._com_port_combo, 0, 1)
        
        self._refresh_btn = QPushButton("刷新")
        self._refresh_btn.setFixedWidth(50)
        self._refresh_btn.clicked.connect(self._on_refresh_ports)
        layout.addWidget(self._refresh_btn, 0, 2)
        
        # 波特率配置
        baud_label = QLabel("波特率:")
        baud_label.setFixedWidth(60)
        layout.addWidget(baud_label, 0, 3)
        
        self._baudrate_combo = QComboBox()
        self._baudrate_combo.setMinimumWidth(100)
        self._baudrate_combo.addItems(["1000000", "500000", "250000", "125000", "100000", "50000"])
        self._baudrate_combo.setCurrentText("500000")
        self._baudrate_combo.setEditable(True)
        layout.addWidget(self._baudrate_combo, 0, 4)
        
        # 发送CAN ID配置（10进制）
        tx_label = QLabel("发送ID:")
        tx_label.setFixedWidth(60)
        layout.addWidget(tx_label, 0, 5)
        
        self._tx_can_id_combo = QComboBox()
        self._tx_can_id_combo.setMinimumWidth(80)
        self._tx_can_id_combo.setEditable(True)
        self._tx_can_id_combo.addItems(["1", "2", "3", "4", "5"])  # 1-64范围的默认值
        self._tx_can_id_combo.setCurrentText("1")  # 默认为1
        
        # 设置10进制验证器
        decimal_validator = DecimalValidator(1, 64)  # 1-64范围
        self._tx_can_id_combo.lineEdit().setValidator(decimal_validator)
        
        layout.addWidget(self._tx_can_id_combo, 0, 6)
        
        # 接收CAN ID配置（固定为0，不可更改）
        rx_label = QLabel("接收ID:")
        rx_label.setFixedWidth(60)
        layout.addWidget(rx_label, 0, 7)
        
        self._rx_can_id_combo = QComboBox()
        self._rx_can_id_combo.setMinimumWidth(80)
        self._rx_can_id_combo.setEditable(False)  # 不可编辑
        self._rx_can_id_combo.addItem("0")
        self._rx_can_id_combo.setCurrentText("0")
        self._rx_can_id_combo.setEnabled(False)  # 禁用
        self._rx_can_id_combo.setStyleSheet("""
            QComboBox:disabled {
                background-color: #f5f5f5;
                color: #7f8c8d;
                border: 1px solid #bdc3c7;
            }
        """)
        
        layout.addWidget(self._rx_can_id_combo, 0, 8)
        
        # 设置列拉伸，最后一列拉伸
        layout.setColumnStretch(9, 1)
        
        return group
    
    def _create_control_layout(self):
        """创建控制按钮布局"""
        layout = QHBoxLayout()
        
        # 连接按钮
        self._connect_btn = QPushButton("连接")
        self._connect_btn.setFixedHeight(35)
        self._connect_btn.setFixedWidth(100)
        self._connect_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 5px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #21618c;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
        """)
        self._connect_btn.clicked.connect(self._on_connect)
        layout.addWidget(self._connect_btn)
        
        # 断开连接按钮
        self._disconnect_btn = QPushButton("断开连接")
        self._disconnect_btn.setFixedHeight(35)
        self._disconnect_btn.setFixedWidth(100)
        self._disconnect_btn.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                border: none;
                border-radius: 5px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
            QPushButton:pressed {
                background-color: #6c7b7d;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
        """)
        self._disconnect_btn.clicked.connect(self._on_disconnect)
        layout.addWidget(self._disconnect_btn)
        
        layout.addStretch()
        
        return layout
    
    def _create_status_group(self):
        """创建状态显示区域"""
        group = QGroupBox("连接状态")
        layout = QHBoxLayout()
        group.setLayout(layout)
        
        # 状态指示器
        status_indicator = QLabel("●")
        status_indicator.setFixedWidth(20)
        status_indicator.setAlignment(Qt.AlignCenter)
        status_indicator.setStyleSheet("color: #e74c3c; font-size: 16px; font-weight: bold;")
        self._status_indicator = status_indicator
        layout.addWidget(status_indicator)
        
        # 状态文本
        self._status_label = QLabel("未连接")
        self._status_label.setStyleSheet("color: #7f8c8d; font-weight: bold;")
        layout.addWidget(self._status_label)
        
        layout.addStretch()
        
        return group
    
    def _on_connect(self):
        """连接按钮点击事件"""
        if self._is_connecting:
            return
        
        # 获取配置
        config = {
            'com_port': self._com_port_combo.currentText(),
            'tx_can_id': self._tx_can_id_combo.currentText(),
            'rx_can_id': self._rx_can_id_combo.currentText(),
            'baudrate': int(self._baudrate_combo.currentText())
        }
        
        # 验证配置
        if config['com_port'] == "请选择COM口" or not config['com_port']:
            return
        
        # 发送连接请求信号
        self.connect_requested.emit(config)
    
    def _on_disconnect(self):
        """断开连接按钮点击事件"""
        self.disconnect_requested.emit()
    
    def _on_refresh_ports(self):
        """刷新COM口按钮点击事件"""
        self.refresh_ports_requested.emit()
    
    def _update_button_states(self):
        """更新按钮状态"""
        has_valid_config = (
            self._com_port_combo.currentText() != "请选择COM口" and
            self._com_port_combo.currentText().strip() != ""
        )
        
        self._connect_btn.setEnabled(has_valid_config and not self._is_connected and not self._is_connecting)
        self._disconnect_btn.setEnabled(self._is_connected)
        
        # 连接时禁用配置控件
        config_enabled = not self._is_connected and not self._is_connecting
        self._com_port_combo.setEnabled(config_enabled)
        self._tx_can_id_combo.setEnabled(config_enabled)
        self._rx_can_id_combo.setEnabled(config_enabled)
        self._baudrate_combo.setEnabled(config_enabled)
        self._refresh_btn.setEnabled(config_enabled)
    
    def set_com_ports(self, ports):
        """设置COM口列表
        
        Args:
            ports: COM口列表
        """
        current_port = self._com_port_combo.currentText()
        self._com_port_combo.clear()
        
        if ports:
            self._com_port_combo.addItems(ports)
            # 尝试保持之前选择的端口
            if current_port in ports:
                self._com_port_combo.setCurrentText(current_port)
        else:
            self._com_port_combo.addItem("无可用COM口")
        
        self._update_button_states()
    
    def set_can_id_options(self, can_ids):
        """设置CAN ID选项
        
        Args:
            can_ids: CAN ID列表（10进制字符串）
        """
        if can_ids:
            # 保存当前值
            current_tx = self._tx_can_id_combo.currentText()
            
            # 更新发送ID选项（接收ID固定为0，不需要更新）
            self._tx_can_id_combo.clear()
            self._tx_can_id_combo.addItems(can_ids)
            
            # 恢复当前值
            if current_tx:
                self._tx_can_id_combo.setCurrentText(current_tx)
    
    def set_connection_config(self, config):
        """设置连接配置
        
        Args:
            config: 包含com_port, tx_can_id, rx_can_id, baudrate的字典
        """
        if 'com_port' in config and config['com_port']:
            index = self._com_port_combo.findText(config['com_port'])
            if index >= 0:
                self._com_port_combo.setCurrentIndex(index)
        
        if 'tx_can_id' in config and config['tx_can_id']:
            self._tx_can_id_combo.setCurrentText(str(config['tx_can_id']))  # 确保是字符串
        
        # 接收ID始终为0，不需要设置
        
        if 'baudrate' in config and config['baudrate']:
            self._baudrate_combo.setCurrentText(str(config['baudrate']))
        
        self._update_button_states()
    
    def set_connection_status(self, connected, status_message=""):
        """设置连接状态
        
        Args:
            connected: 是否已连接
            status_message: 状态消息
        """
        self._is_connected = connected
        self._is_connecting = False
        
        if connected:
            self._status_indicator.setStyleSheet("color: #27ae60; font-size: 16px; font-weight: bold;")
            self._status_label.setText(status_message or "已连接")
            self._status_label.setStyleSheet("color: #27ae60; font-weight: bold;")
        else:
            self._status_indicator.setStyleSheet("color: #e74c3c; font-size: 16px; font-weight: bold;")
            self._status_label.setText(status_message or "未连接")
            self._status_label.setStyleSheet("color: #e74c3c; font-weight: bold;")
        
        self._update_button_states()
    
    def set_connecting_status(self, message="正在连接..."):
        """设置连接中状态
        
        Args:
            message: 连接状态消息
        """
        self._is_connecting = True
        self._status_indicator.setStyleSheet("color: #f39c12; font-size: 16px; font-weight: bold;")
        self._status_label.setText(message)
        self._status_label.setStyleSheet("color: #f39c12; font-weight: bold;")
        
        self._connect_btn.setText("连接中...")
        self._update_button_states()
    
    def reset_connect_button(self):
        """重置连接按钮"""
        self._connect_btn.setText("连接")
        self._is_connecting = False
        self._update_button_states()
    
    def get_current_config(self):
        """获取当前配置
        
        Returns:
            dict: 当前连接配置
        """
        return {
            'com_port': self._com_port_combo.currentText(),
            'tx_can_id': self._tx_can_id_combo.currentText(),  # 10进制字符串
            'rx_can_id': "0",  # 固定为0
            'baudrate': int(self._baudrate_combo.currentText()) if self._baudrate_combo.currentText().isdigit() else 500000
        }